package com.osilon;

import java.io.BufferedReader;
import java.io.File;
import java.io.IOException;
import java.io.InputStreamReader;
import java.lang.reflect.Constructor;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.logging.Logger;

import com.osilon.hooks.MinecraftServer;
import com.osilon.updater.Updater;
import com.osilon.util.Downloader;
import com.osilon.util.PluginCache;


public class Osilon {
	private Logger logger = Logger.getLogger("Osilion");
	private static ClassLoader loader;
	private static MinecraftServer server;
	private static PluginCache plugins;
	
	private static void printUsage() {
		System.out.println("Usage: java -jar Osilion.jar [-f]");
		System.out.println("\t-f\tForce an update of the minecraft_server.jar");
	}
	
	public static void main(String[] args) {
		boolean forceUpdate = false, showGui = true;
		
		for(String arg : args){
			if(arg.equals("-f")) {
				forceUpdate = true;
			} else if (arg.equals("nogui")) {
				showGui = false;
			} else {
				printUsage();
			}
		} 
		
		Osilon methane = new Osilon(forceUpdate);
		methane.startServer(showGui);
		
		while(server.getServerProperties() == null);
		
		methane.setupPlugins();
	}
	
	public Osilon(boolean forceUpdate) {
		File f = new File("minecraft_server.jar");
		
		if(forceUpdate || !f.exists()) {
			if(forceUpdate) {
				logger.info("Forcing an update of the minecraft_server.jar");
				
				f.delete();
			} else {
				logger.info("No minecraft_server.jar found. Would you like to download the current server?");
				
				BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
				
				try {
					System.out.print("> ");
					String line = reader.readLine();

				
					if(Character.toLowerCase(line.charAt(0)) != 'y') {
						throw new RuntimeException("minecraft_server.jar not found.");
					}
				} catch (IOException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			}
			
			try {
				Downloader.download(new URL("https://s3.amazonaws.com/MinecraftDownload/launcher/minecraft_server.jar"));
			} catch (MalformedURLException e) {
				e.printStackTrace();
			}
		}

		loader = new OsilonClassLoader();
	}
	
	public void startServer(boolean showGui) {
		try {
			Class<?> cMinecraftServer = loader.loadClass("net.minecraft.server.MinecraftServer");
			Object minecraftServer = cMinecraftServer.newInstance();
			Class<?> cBc = loader.loadClass((String) Updater.getInfoMap().get("ServerThread"));
			Constructor<?> c = cBc.getConstructor(String.class, cMinecraftServer);
		 	Object bc = c.newInstance("Server thread", minecraftServer);
			cBc.getMethod("start").invoke(bc);
			
			server = (MinecraftServer) minecraftServer;
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
	
	public void setupPlugins() {
		File pluginDir = new File(server.getServerProperties().getString("plugin-dir", "plugins"));
	
		if(!pluginDir.exists()) pluginDir.mkdirs();
		
		plugins = new PluginCache(pluginDir);
		plugins.loadPlugins();
	}

	public static ClassLoader getClassLoader() {
		return loader;
	}
	
	public static PluginCache getPluginCache() {
		return plugins;
	}
	
	public static MinecraftServer getMinecraftServer() {
		return server;
	}
}
